import { loginByUsername, logout, getMenus } from '@/api/login'
import { getToken, setToken, removeToken, getUserName, setUserName, removeUserName } from '@/utils/auth'
import i18n from '@/lang'

function formatMenus(menus) {
  const mainPage = {
    menuId: 'mainPage',
    url: '/home',
    icon: 'iconfont icon-home',
    name: 'mainPage',
    menuName: i18n.t('common.mainPage')
  }
  const newMenus = [mainPage]
  return newMenus.concat(menus)
}
const user = {
  state: {
    token: getToken(),
    name: getUserName(),
    menus: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response.data.data
          commit('SET_TOKEN', data.token)
          commit('SET_NAME', data.userName)
          commit('SET_MENUS', [])
          setToken(data.token)
          setUserName(data.userName)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getMenus({ commit }) {
      return new Promise((resolve, reject) => {
        getMenus().then(response => {
          const menus = response.data.data
          const newMenus = formatMenus(menus)
          commit('SET_MENUS', newMenus)
          resolve(menus)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_MENUS', [])
          removeToken()
          removeUserName()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }

  }
}

export default user
